<template>
  <div>
    <div>
      <AIText :raw-content="chatString"></AIText>
    </div>
    <div>
      <el-input
        v-model="input"
        style="width: 1"
        placeholder="Please input"
        @keydown.enter.native="sendMessage"
      >
        <template #append>
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </template>
      </el-input>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { SSE } from "sse.js";
import { ref } from "vue";
import AIText from "./AIText.vue";
import { useAuthStore } from "@/stores/auth";
import { ChatResponse } from "@/types/chat";

const input = ref("");
const chatString = ref("");
const sendMessage = async () => {
  chatString.value = "";

  const authStore = useAuthStore();
  const evtSource = new SSE("http://localhost:9090/ai/PostSSEStream", {
    withCredentials: true,
    // 禁用自动启动，需要调用stream()方法才能发起请求
    start: false,
    headers: { "Content-Type": "application/json", token: authStore.token },
    payload: input.value,
    method: "POST",
  });
  evtSource.addEventListener("message", async (event: any) => {
    const response = JSON.parse(event.data) as ChatResponse;
    const finishReason = response.result.metadata.finishReason;
    if (response.result.output.text) {
      chatString.value = chatString.value + response.result.output.text;
      console.log(chatString.value);
    }
  });

  input.value = "";
  // 调用stream，发起请求。
  evtSource.stream();
};
</script>

<style>
</style>

